class Cpanel::ProductsController < Cpanel::BaseController

  before_filter :find_product, only: [:show, :edit, :update, :destroy]

  def index
    @products = Product.by_created_at_desc.paginate(page: params[:page])
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create

    @product = Product.new product_params

    if @product.save
      if params[:photo]
        params[:photo].each do |photo|
          Photo.create(path: photo, photoable: @product)
        end
      end
      redirect_to [:cpanel, @product], notice: 'created success'
    else
      flash[:notice] = 'created failed'
      render 'new'
    end
  end

  def edit
  end

  def update
    if params[:product][:logo_img].blank?
      params[:product].delete :logo_img
    end

    if @product.update_attributes(product_params)

      if params[:photo]
        params[:photo].each do |photo|
          Photo.create(path: photo, photoable: @product)
        end
      end

      redirect_to [:cpanel, @product], notice: 'updated success'
    else
      flash[:notice] = 'update failed'
      render 'edit'
    end

  end

  def destroy
    @product.destroy
    redirect_to cpanel_products_path,  notice: 'delete success'
  end

  private

  def find_product
    @product = Product.find(params[:id])
  end

  def update_photo(photo_ids)
  end

  def product_params
    params.require(:product).permit(:title, :description, :language, :logo_img)
  end
end
